#include <am.h>
#include <klib.h>
#include <klib-macros.h>
#include <stdarg.h>

#if !defined(__ISA_NATIVE__) || defined(__NATIVE_USE_KLIB__)

int int_to_string(int n, char*buf1);
int printf(const char *fmt, ...) {
		va_list ap;
		char *sval;
		size_t cnt = 0;
		va_start(ap,fmt);
		for(;*fmt;fmt++){
			if(*fmt != '%'){
				putch(*fmt);		
				cnt ++;
				continue;
			}
			switch(*++fmt){
				case 's':{
						for(sval = va_arg(ap,char*);*sval;sval++){
							putch(*sval);
							cnt++;
						}
						break;}
				case 'd':{
						char buf1[20] = {};
						memset(buf1,'\0',20);
						int_to_string(va_arg(ap,int),buf1);		
						for(sval = buf1;*sval;sval++){
							putch(*sval);
							cnt++;
						}
						break;
						}
				default: {break;}//{panic("function printf not completed");break;}
			}
		}
		putch('\0');
		va_end(ap);
		return cnt-1;
}
int vsprintf(char *out, const char *fmt, va_list ap) {
  panic("Not implemented");
}

int int_to_string(int n, char*buf1){
	char buf[20] = {};
	int i = 0;
	int n1 = n;
	if(n<0) n1 = -n;
	memset(buf,'\0',20);
	do{
	 buf[i] =	n1%10 + '0';
	 i++;
	 n1 = n1/10;
	}	while(n1!=0);
	if(n<0) {buf[i] = '-';i++;}
	int j = 0;
	for(;i>0;i--)
	{
		buf1[j] = buf[i-1];
		j++;
	}
	buf1[j] = '\0';	
	return i;
}
int sprintf(char *out, const char *fmt, ...) {
		va_list ap;
		char *sval;
		size_t cnt = 0;
		va_start(ap,fmt);
		for(;*fmt;fmt++){
			if(*fmt != '%'){
				*(out+cnt) = *fmt;		
				cnt ++;
				continue;
			}
			switch(*++fmt){
				case 's':{
						for(sval = va_arg(ap,char*);*sval;sval++){
							*(out+cnt) = *sval;
							cnt++;
						}
						break;}
				case 'd':{
						char buf1[20] = {};
						memset(buf1,'\0',20);
						int_to_string(va_arg(ap,int),buf1);		
						for(sval = buf1;*sval;sval++){
							*(out+cnt) = *sval;
							cnt++;
						}
						break;
						}
				default: {panic("not completed");break;}
			}
		}
		*(out+cnt) = '\0';
		va_end(ap);
		return cnt-1;
}

int snprintf(char *out, size_t n, const char *fmt, ...) {
  panic("Not implemented");
}

int vsnprintf(char *out, size_t n, const char *fmt, va_list ap) {
  panic("Not implemented");
}

#endif
